<!--
 * @Author: liangkun 2669681641@qq.com
 * @Date: 2023-08-22 13:55:38
 * @LastEditors: liangkun 2669681641@qq.com
 * @LastEditTime: 2023-09-08 15:35:13
 * @FilePath: \radiation-hygiene-fe\src\views\system\ukey\components\bindUser.vue
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<template>
  <el-dialog
    :title="bindUserTitle"
    v-if="dialogVisible"
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <!-- <el-form-item label="印章类型" prop="sealType">
        <el-select v-model="form.sealType" placeholder="请选择印章类型">
          <el-option
            v-for="item in sealTypeLists"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <template v-if="form.sealType != 1">
        <el-form-item label="绑定人员" prop="user">
          <m-select
            v-model="form.user"
            clearable
            filterable
            :disabled="selectDisabled"
            placeholder="输入文字检索查询"
            :lists="userLists"
            lists_label="userName"
            lists_vice_label="nickName"
            lists_value="userId"
            :total="total"
            :pageSize="1000"
            @handleChange="listeningEvent"
          />
        </el-form-item>
        <el-form-item label="设置密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="启动页" prop="startUrl">
          <el-input v-model="form.startUrl" placeholder="请输入" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="">
          <el-switch
            style="display: inline-flex"
            v-model="form.state"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </el-form-item> -->
      </template>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmitEvent">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listUser } from "@/api/system/user";
import { startUrl, saveUkey } from "@/api/system/ukey";
import MSelect from '@/components/mSelect'
import cipherDog from '@/utils/cipherDog'
import {getUUID} from '@/utils/uuid'
const {Syunew6W} = cipherDog
export default {
  name: 'BindUser',
  components: {
    MSelect
  },
  data() {
    return {
      bindUserTitle: '',
      selectDisabled: false,
      dialogVisible: false,
      userLists: [],
      startUrlList: [],
      total: 0,
      sealTypeLists: [
        {
          label: '私章',
          value: '0'
        },
        {
          label: '公章',
          value: '1'
        },
      ],
      form: {
        sealType: '0',
        state: 0
      },
      rules: {
        sealType: [
          { required: true, trigger: ["blur", "change"], message: "请选择印章类型" }
        ],
        user: [
          { required: true, trigger: ["blur", "change"], message: "请选择绑定人员" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入密码" }
        ],
        startUrl: [
          { required: true, trigger: "blur", message: "请输入自动跳转链接" }
        ]
      },

    }
  },
  methods: {
    async openDialog(data) {
      this.reset()
      let {userId, state} = data || {}
      this.getStartUrl()
      await this.listeningEvent({
        pageSize: 10000
      })
      this.bindUserTitle = '新增'
      // 修改回显
      this.form = data
      if (userId) {
        this.bindUserTitle = '修改'
        this.selectDisabled = true
        this.$set(this.form, 'user', Number(userId))
      }
      this.$set(this.form, 'state', String(state))
      this.dialogVisible = true
    },
    getUserLists() {

    },
    handleClose() {
      // this.reset()
    },
    handleSubmitEvent() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let lists= await Syunew6W.getInfoLists()

          if (lists.length == 0) {
            this.$message.warning('请插入UKEY')
            return
          }
          if (lists.length > 1) {
            this.$message.warning('请拔出多余UKEY')
            return
          }
          console.log(this.form, lists[0]);
          const loading = this.$loading({
            lock: true,
            text: '设置中 请勿拔出 否则会损坏u盘',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          let {
            chip_id,
            devicPath,
            expand_version,
            ukey_id,
            version
          } = lists[0]
          console.log(this.form);
          let {startUrl, password, user, sealType, id, state} = this.form
          let encryptionStr = JSON.stringify({
            sealType
          }) // 写入加密后字符串
          let data = {
            ukeyId: ukey_id, // 锁id
            chipId: chip_id, // 芯片ID
            version, // 锁的版本
            expandVersion: expand_version, // 拓展版本
            userId: user, // 用户ID
            // secretKeyOne: '', // (增强)密钥一
            // secretKeyTwo: '', // (增强)密钥二
            password, // 密码
            startUrl, // 启动URl
            encryptionStr, // 写入加密后字符串
            // readPassword: '', // 读密码
            // writePassword: '', // 写密码
            state: Number(state), // 状态（0正常 1停用）
          }
          if (id) data.id = id

          saveUkey(data).then(async ({code, data, msg}) => {
            if (code == '200') {
              let findLoginName = this.userLists.find(i => i.userId == user)?.userName || ''
              // 设置账号密码‘
              try {
                await Syunew6W.setNameAndPass({
                  devicPath: devicPath,
                  name: findLoginName,
                  password: password
                })
                // 设置插入u盘自动跳转网站   需要插件
                await Syunew6W.setWebUrl({
                  devicPath: devicPath,
                  url: startUrl
                })

                // 添加数据普通算法
                await Syunew6W.setKeyData({
                  devicPath: devicPath,
                  dataString: encryptionStr
                })

                this.$message.success('绑定成功')
                this.$emit('handleAddUkey')
                this.reset()
              } catch (error) {
                console.log(error);
                this.$message.warning('绑定失败')
              }
              this.dialogVisible = false
              loading.close()
            } else {
              this.$message.warning(msg)
            }
          }).catch(err => {
            // this.$message.warning('接口错误  请联系管理员')
            loading.close()
          })
        }
      })
    },
    listeningEvent(e) {
      let {queryName, pageNum, pageSize} = e
      let query = {
        status: 0,
        pageNum,
        pageSize,
        userName: queryName
      }
      listUser(query).then(response => {
          this.userLists = response.rows;
          this.total = response.total;
        }
      );
    },
    getStartUrl() {
      startUrl().then(res => {
        this.form.startUrl = res.data
      })
    },
    reset() {
      this.form = {
        sealType: '0',
      }
      this.selectDisabled = false
    }
  }
}
</script>

<style>

</style>
